const express = require("express");
const multer = require("multer");
const path = require("path");
const fs = require("fs");
const app = express();

// app.use(express.static("../frontend"));

const upload = multer(); // 暂不配置storage，先接收文件到内存

app.post(
  "/upload",
  upload.fields([{ name: "files" }, { name: "paths" }]),
  async (req, res) => {
    const files = req.files["files"];
    let paths = req.body["paths"];

    if (!Array.isArray(paths) && typeof paths === "string") {
      paths = [paths];
    }

    try {
      // 并行处理文件上传
      await Promise.all(
        files.map((file, index) => {
          const targetPath = path.join(__dirname, "uploads", paths[index]);
          const dir = path.dirname(targetPath);

          // 检查目录是否存在，不存在则创建
          return fs.promises
            .mkdir(dir, { recursive: true })
            .then(() => fs.promises.writeFile(targetPath, file.buffer));
        })
      );
      res.send("Files uploaded successfully.");
    } catch (error) {
      console.error("Failed to upload files:", error);
      res.status(500).send("Error uploading files");
    }
  }
);

app.listen(3000, () => console.log("Server started on port 3000"));
